package com.event.content;

import java.io.IOException;
import java.lang.reflect.Field;

import com.example.logindesign.Mainmenu;
import com.example.logindesign.R;

import android.R.integer;
import android.R.string;
import android.app.ActionBar;
import android.app.Activity;
import android.app.TaskStackBuilder;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.NavUtils;
import android.support.v7.app.ActionBarActivity;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View.OnClickListener;
import android.view.ViewConfiguration;
import android.widget.Toast;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.LinkedList;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.ksoap2.SoapEnvelope;
import org.ksoap2.serialization.SoapObject;
import org.ksoap2.serialization.SoapSerializationEnvelope;
import org.ksoap2.transport.HttpTransportSE;
import org.xmlpull.v1.XmlPullParserException;

import android.os.AsyncTask;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.TextView;
import com.handmark.pulltorefresh.library.PullToRefreshBase;
import com.handmark.pulltorefresh.library.PullToRefreshBase.Mode;
import com.handmark.pulltorefresh.library.PullToRefreshBase.OnRefreshListener2;
import com.handmark.pulltorefresh.library.PullToRefreshListView;

public class EventListViewActivity extends Activity {
	private static final String NAMESPACE = "http://tempuri.org/";
	private static final String ENDPOINT = "192.168.1.198:1536/CommunitySystemsicWsWF.asmx";
	private LinkedList<String> mListItems;
	private ArrayList<HashMap<String, Object>> listItemArrayList;
	// 添加按钮
	private Button btnAdd;
	// 返回按钮
	private ImageButton btnBack;
	// 上拉刷新的控件
	private PullToRefreshListView mPullRefreshListView;
	private ArrayAdapter<String> mAdapter;
	private SimpleAdapter simpleAdapter;
	// 下边页数显示相关控件
	private TextView totalPageTextView;
	private TextView pageTextView;
	private TextView recordsTextView;
	// 总条数
	private int records = 0;
	// 总页数
	private int totalPage = 0;
	// 显示的条数
	private int rows = 10;
	// 当前页数
	private int page = 1;
	// unitcode
	private String unitcode = "3707250102";
	// 画面控件相关,目前先用事件类型，发现场所和登记时间
	private String id;
	private String unit;
	private String shijianleixing;
	private String shijianleibie;
	private String lianxifangshi;
	private String faxianchangsuo;
	private String dengjishijian;
	private String banlizhuangtai;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.layout_event_listview);
		// forceShowOverflowMenu();
		// ActionBar actionBar = getActionBar();
		// actionBar.setDisplayHomeAsUpEnabled(true);
		// 得到控件
		totalPageTextView = (TextView) findViewById(R.id.txt_event_totalPage);
		pageTextView = (TextView) findViewById(R.id.txt_event_page);
		recordsTextView = (TextView) findViewById(R.id.txt_event_records);
		btnBack = (ImageButton) findViewById(R.id.btn_event_list_back);
		btnBack.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				// 跳转到menu页面
				skipMainMenuActivity();
			}
		});
		btnAdd = (Button) findViewById(R.id.btn_event_add);
		btnAdd.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				// 跳转到添加页面
				skipAddActivity();
			}
		});
		mPullRefreshListView = (PullToRefreshListView) findViewById(R.id.pull_refresh_list);
		mPullRefreshListView.setMode(Mode.BOTH);
		// 初始化数据
		initDatas();
		new InitDatas().execute();
		// // 设置适配器
		// mAdapter = new ArrayAdapter<String>(this,
		// android.R.layout.simple_list_item_1, mListItems);
		// mPullRefreshListView.setAdapter(mAdapter);
		simpleAdapter = new SimpleAdapter(EventListViewActivity.this,
				listItemArrayList, R.layout.listview_style_event, new String[] {
						"ItemID", "ItemTitle", "ItemText", "ItemTime" },
				new int[] { R.id.ItemID, R.id.ItemTitle, R.id.ItemText,
						R.id.ItemTime });
		mPullRefreshListView.setAdapter(simpleAdapter);
		mPullRefreshListView.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> parent, View view,
					int position, long id) {
				// TODO Auto-generated method stub
				// Toast.makeText(ListViewActivity.this, arg2 + "+" + arg3,
				// Toast.LENGTH_LONG).show();
				// TextView titleTextView = (TextView) view
				// .findViewById(R.id.ItemTitle);
				// TextView contentTextView = (TextView) view
				// .findViewById(R.id.ItemText);
				// String string = titleTextView.getText().toString();
				// Toast.makeText(EventListViewActivity.this, string,
				// Toast.LENGTH_LONG).show();
				TextView idTextView = (TextView) view.findViewById(R.id.ItemID);
				String eventID = idTextView.getText().toString();
				// 跳转到详细页面
				skipDetailActivity(eventID);
			}
		});

		mPullRefreshListView
				.setOnRefreshListener(new OnRefreshListener2<ListView>() {
					@Override
					public void onPullDownToRefresh(
							PullToRefreshBase<ListView> refreshView) {
						Log.e("TAG", "onPullDownToRefresh");
						// 这里写下拉刷新的任务 page初始化为1
						page = 1;
						new GetDataTask().execute();
					}

					@Override
					public void onPullUpToRefresh(
							PullToRefreshBase<ListView> refreshView) {
						Log.e("TAG", "onPullUpToRefresh");
						// 这里写上拉加载更多的任务 page++
						page++;
						new GetDataTask().execute();
					}
				});
	}

	/**
	 * 设定即使手机物理menu键，仍显示overflow按钮
	 */
	private void forceShowOverflowMenu() {
		try {
			ViewConfiguration config = ViewConfiguration.get(this);
			Field menuKeyField = ViewConfiguration.class
					.getDeclaredField("sHasPermanentMenuKey");
			if (menuKeyField != null) {
				menuKeyField.setAccessible(true);
				menuKeyField.setBoolean(config, false);
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	/**
	 * 跳转到mainmenu页面
	 */
	private void skipMainMenuActivity() {
		Intent mainmenuIntent = new Intent();
		mainmenuIntent
				.setClass(EventListViewActivity.this, Mainmenu.class);
		//如果前面的activity 没有主动finish 推到栈顶，不然画面会刷一下
		//mainmenuIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
		EventListViewActivity.this.startActivity(mainmenuIntent);
		EventListViewActivity.this.finish();
	}

	
	/**
	 * 跳转到增加页面，并传入相应参数和标识
	 */
	private void skipAddActivity() {
		Intent editIntent = new Intent();
		editIntent.putExtra("operateFlag", "Add");
		editIntent
				.setClass(EventListViewActivity.this, EventEditActivity.class);
		EventListViewActivity.this.startActivity(editIntent);
		EventListViewActivity.this.finish();
	}

	/**
	 * 跳转到详细页面，并传入相应参数
	 */
	private void skipDetailActivity(String id) {
		Intent detailIntent = new Intent();
		detailIntent.putExtra("eventID", id);
		detailIntent.putExtra("unitcode", unitcode);
		detailIntent.setClass(EventListViewActivity.this,
				EventDetailActivity.class);
		EventListViewActivity.this.startActivity(detailIntent);
		EventListViewActivity.this.finish();
	}

	/**
	 * 初始化控件值，必须有，防止ui阻塞
	 */
	private void initDatas() {
		// TextView 更新
		textViewUpdate();
		// listview
		listItemArrayList = new ArrayList<HashMap<String, Object>>();
		HashMap<String, Object> map = new HashMap<String, Object>();
		map.put("ItemID", "");
		map.put("ItemTitle", "");
		map.put("ItemText", "");
		map.put("ItemTime", "");
		listItemArrayList.add(map);
	}

	/**
	 * 更新页码等控件显示
	 */
	private void textViewUpdate() {
		totalPageTextView.setText("总页数:" + String.valueOf(totalPage));
		pageTextView.setText("当前页码:" + String.valueOf(page));
		recordsTextView.setText("总条数:" + String.valueOf(records));
	}

	/**
	 * 上拉下拉更新线程
	 * 
	 * @author Administrator
	 * 
	 */
	private class GetDataTask extends
			AsyncTask<Void, Void, ArrayList<HashMap<String, Object>>> {

		@Override
		protected ArrayList<HashMap<String, Object>> doInBackground(
				Void... params) {
			String resultString = getEventList();
			ArrayList<HashMap<String, Object>> finallyResult = jsonFormat(resultString);
			return finallyResult;
		}

		protected void onPostExecute(
				ArrayList<HashMap<String, Object>> finallyResultArrayList) {
			if (finallyResultArrayList.size() > 0) {
				if (page == 1) {
					listItemArrayList.clear();
				}
				listItemArrayList.addAll(finallyResultArrayList);
			}
			if (page > totalPage) {
				// 提示最后一页，page设置为totalpage
				page = totalPage;
				Toast.makeText(EventListViewActivity.this, "已经是最后一页",
						Toast.LENGTH_LONG).show();
			}
			// TextView 更新
			textViewUpdate();

			simpleAdapter.notifyDataSetChanged();
			// Call onRefreshComplete when the list has been refreshed.
			mPullRefreshListView.onRefreshComplete();
		}
	}

	/**
	 * 数据初始化
	 * 
	 * @author Administrator
	 * 
	 */
	private class InitDatas extends
			AsyncTask<Void, Void, ArrayList<HashMap<String, Object>>> {

		@Override
		protected void onPreExecute() {
			Log.e(null, "数据加载中");
			listItemArrayList.clear();
			HashMap<String, Object> map = new HashMap<String, Object>();
			map.put("ItemTitle", "数据加载中,请稍等。");
			listItemArrayList.add(map);
		}

		@Override
		protected ArrayList<HashMap<String, Object>> doInBackground(
				Void... params) {
			String resultString = getEventList();
			ArrayList<HashMap<String, Object>> finallyResult = jsonFormat(resultString);
			return finallyResult;
		}

		protected void onPostExecute(
				ArrayList<HashMap<String, Object>> finallyResultArrayList) {
			// TextView 更新
			textViewUpdate();
			listItemArrayList.clear();
			listItemArrayList.addAll(finallyResultArrayList);
			simpleAdapter.notifyDataSetChanged();
			// Call onRefreshComplete when the list has been refreshed.
			mPullRefreshListView.onRefreshComplete();
		}
	}

	/**
	 * 连接webservice，得到字符串
	 * 
	 * @return
	 */
	private String getEventList() {
		String resultString = "";
		Log.e(null, Thread.currentThread().getName() + "事件列表线程");
		String methodName = "get_SysGridMyEvent";
		String soapAcion = "http://tempuri.org/get_SysGridMyEvent";
		SoapObject soapObject = new SoapObject(NAMESPACE, methodName);

		soapObject.addProperty("unitcode", unitcode);
		soapObject.addProperty("rows", rows);
		soapObject.addProperty("page", page);

		SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(
				SoapEnvelope.VER11);
		envelope.setOutputSoapObject(soapObject);
		envelope.dotNet = true;
		HttpTransportSE transportSE = new HttpTransportSE(ENDPOINT);
		try {
			transportSE.call(soapAcion, envelope);
			if (envelope.getResponse() != null) {
				SoapObject object = (SoapObject) envelope.bodyIn;
				resultString = object.getProperty(0).toString();
			}
			Log.e("结果page", String.valueOf(page));
			Log.e("结果", resultString);
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (XmlPullParserException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return resultString;
	}

	/**
	 * 解析json数据返回hashmap格式数据
	 * 
	 * @return
	 */
	private ArrayList<HashMap<String, Object>> jsonFormat(String resultString) {
		ArrayList<HashMap<String, Object>> tempArrayList = new ArrayList<HashMap<String, Object>>();
		JSONArray jsonArray;
		try {
			jsonArray = new JSONArray(resultString);
			int len = jsonArray.length();
			JSONObject jsonObject = jsonArray.optJSONObject(0);
			if (jsonObject.optString("Code").equals("1")) {
				JSONObject totalJsonObject = jsonArray.optJSONObject(1);
				totalPage = Integer.valueOf(totalJsonObject.optString("total"))
						.intValue();
				records = Integer.valueOf(totalJsonObject.optString("records"))
						.intValue();
				// 根据实际从第2(3)组开始取得有关数据
				for (int i = 2; i < len; i++) {
					jsonObject = jsonArray.optJSONObject(i);
					HashMap<String, Object> map = new HashMap<String, Object>();
					map.put("ItemID", jsonObject.optString("id"));
					map.put("ItemTime", jsonObject.optString("dengjishijian"));
					map.put("ItemTitle", jsonObject.optString("shijianleixing"));
					map.put("ItemText", jsonObject.optString("faxianchangsuo"));
					tempArrayList.add(map);
				}
			} else {
				// 没有数据，如何显示？已经到最后了
				// map.put("ItemTime", R.drawable.icon_settings);
				// map.put("ItemTitle", "xin这是第" + mItemCount + "行");
				// map.put("ItemText", "xin这是第" + mItemCount + "行");
			}
		} catch (JSONException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return tempArrayList;
	}

	/**
	 * 重写keydown事件
	 */
	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		if (keyCode == KeyEvent.KEYCODE_BACK) {
			skipMainMenuActivity();
			return true;
		}
		return super.onKeyDown(keyCode, event);
	}
	
	@Override
	protected void onDestroy() {
		super.onDestroy();
	}
}
